package main

import (
	"encoding/json"
	"fmt"
	"path"

	"github.com/gofiber/fiber/v2"
	log "github.com/sirupsen/logrus"
)

type Resize struct {
	Mode    string `query:"m" json:"m,int"` // mode: lfit
	Width   uint   `query:"w" json:"w"`     // width
	Height  uint   `query:"h" json:"h"`     // height
	Quality uint   `query:"q" json:"q"`     // quality
}

func convert(c *fiber.Ctx) error {

	var resize Resize = Resize{
		Mode:    "lfit",
		Width:   0,
		Height:  0,
		Quality: uint(config.Quality),
	}
	if err := c.QueryParser(&resize); err != nil {
		return err
	}
	query, _ := json.Marshal(resize)
	fmt.Printf("%s\n", query)
	var app = path.Clean(c.Params("app"))
	fmt.Println("app", app)

	var reqFileURI = c.Params("*")
	fmt.Println("reqFileURI", reqFileURI)

	ImgPath := config.Input[app]
	fmt.Println("ImgPath", ImgPath)
	// var reqFileURI, _ = url.QueryUnescape(c.Path()) // /mypic/123.jpg

	reqFileURI = path.Clean(reqFileURI)
	var imgFilename = path.Base(reqFileURI) // filename, 123.jpg

	rawImageAbs := path.Join(ImgPath, reqFileURI) // /home/xxx/mypic/123.jpg
	fmt.Println("rawImageAbs", rawImageAbs)
	// 处理原图不存在
	if !imageExists(rawImageAbs) {
		_ = c.SendStatus(404)
		return c.SendString("image not found")
	}
	if !checkAllowedType(imgFilename) {
		msg := "不支持处理的文件发送原图：" + imgFilename
		log.Warn(msg)

		c.Set("ETag", genEtag(rawImageAbs))
		return c.SendFile(rawImageAbs)
	}

	resizeStr := fmt.Sprintf("m_%s_w_%d_h_%d_q_%d", resize.Mode, resize.Width, resize.Height, resize.Quality)

	// 判断是否支持webp
	Supported := guessSupportedFormat(&c.Request().Header)
	// 根据文件修改时间处理文件路径，返回值是两个，一个是webp的路径，一个是原图的路径，两个都可能是原图类型的路径
	outWebpFilePath, baseOutFilenamePath := genOptimizedAbs(rawImageAbs, config.ExhaustPath+"/"+app, imgFilename, reqFileURI, resizeStr)

	if Supported["webp"] {
		if imageExists(outWebpFilePath) {
			var availableFiles = []string{rawImageAbs, baseOutFilenamePath, outWebpFilePath}

			c.Set("ETag", genEtag(rawImageAbs))
			return c.SendFile(findSmallestFiles(availableFiles))
		}
	} else if imageExists(baseOutFilenamePath) {
		var availableFiles = []string{rawImageAbs, baseOutFilenamePath}

		c.Set("ETag", genEtag(rawImageAbs))
		return c.SendFile(findSmallestFiles(availableFiles))
	}

	// 压缩文件
	err := compressImage(rawImageAbs, baseOutFilenamePath, outWebpFilePath, &resize)

	if err != nil {
		// 压缩失败返回源文件
		c.Set("ETag", genEtag(rawImageAbs))
		return c.SendFile(rawImageAbs)
	}

	var availableFiles = []string{rawImageAbs, baseOutFilenamePath}
	if !Supported["webp"] {
		// 对不支持webp的浏览器发送源文件的压缩版
		c.Set("ETag", genEtag(rawImageAbs))

		var finalFile = findSmallestFiles(availableFiles)
		return c.SendFile(finalFile)
	}
	// if img != nil && !imageExists(outWebpFilePath) {
	// 	_ = SaveImage(img, outWebpFilePath, "webp", &resize) // 处理文件
	// }

	if imageExists(outWebpFilePath) && Supported["webp"] {
		availableFiles = append(availableFiles, outWebpFilePath)
	}

	var finalFile = findSmallestFiles(availableFiles)
	etag := genEtag(finalFile)
	c.Set("ETag", etag)
	// // c.Set("X-Compression-Rate", getCompressionRate(rawImageAbs, finalFile))
	// buf, _ := ioutil.ReadFile(finalFile)
	// c.Set("content-type", getFileContentType(buf))
	// return c.SendFile(finalFile)

	c.Set("ETag", genEtag(rawImageAbs))
	return c.SendFile(finalFile)

}
